<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>循环语句 | 如是的学习博客</title><meta name="keywords" content="python"><meta name="author" content="rushiy"><meta name="copyright" content="rushiy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Python 有两个原始的循环命令：  while循环 for循环  while 循环常规用法如果使用while循环，只要条件为真，我们就可以执行一组语句。 12345678910&gt;&gt;&gt; num &#x3D; 5&gt;&gt;&gt; while num:        print(num)        num -&#x3D; 1## 输出结果如下 54321  我们定义了num &#x3D; 5，当执行">
<meta property="og:type" content="article">
<meta property="og:title" content="循环语句">
<meta property="og:url" content="https://rushiy.gitee.io/python/%E5%BE%AA%E7%8E%AF%E8%AF%AD%E5%8F%A5/index.html">
<meta property="og:site_name" content="如是的学习博客">
<meta property="og:description" content="Python 有两个原始的循环命令：  while循环 for循环  while 循环常规用法如果使用while循环，只要条件为真，我们就可以执行一组语句。 12345678910&gt;&gt;&gt; num &#x3D; 5&gt;&gt;&gt; while num:        print(num)        num -&#x3D; 1## 输出结果如下 54321  我们定义了num &#x3D; 5，当执行">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-10-21T16:19:34.000Z">
<meta property="article:author" content="rushiy">
<meta property="article:tag" content="python">
<meta name="twitter:card" content="summary"><link rel="shortcut icon" href="/img/favicon.jpg"><link rel="canonical" href="https://rushiy.gitee.io/python/%E5%BE%AA%E7%8E%AF%E8%AF%AD%E5%8F%A5/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '循环语句',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-11-19 01:18:40'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/favicon.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">28</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">3</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">如是的学习博客</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">循环语句</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-10-21T16:19:34.000Z" title="发表于 2022-10-22 00:19:34">2022-10-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-11-18T17:18:40.693Z" title="更新于 2022-11-19 01:18:40">2022-11-19</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="循环语句"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>Python 有两个原始的循环命令：</p>
<ul>
<li><code>while</code>循环</li>
<li><code>for</code>循环</li>
</ul>
<h2 id="while-循环"><a href="#while-循环" class="headerlink" title="while 循环"></a>while 循环</h2><h3 id="常规用法"><a href="#常规用法" class="headerlink" title="常规用法"></a>常规用法</h3><p>如果使用<code>while</code>循环，只要条件为真，我们就可以执行一组语句。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>num = <span class="number">5</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">while</span> num:</span><br><span class="line">        <span class="built_in">print</span>(num)</span><br><span class="line">        num -= <span class="number">1</span></span><br><span class="line"><span class="comment">## 输出结果如下 </span></span><br><span class="line"><span class="number">5</span></span><br><span class="line"><span class="number">4</span></span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="number">2</span></span><br><span class="line"><span class="number">1</span></span><br></pre></td></tr></table></figure>

<p>我们定义了<code>num = 5</code>，当执行第一次循环时，由于<code>num = 5</code>，<code>while</code>的判断结果为真，因此执行<code>while</code>中的代码块，首先打印<code>num</code>的值，然后执行<code>num -= 1</code>，此时<code>num = 4</code>，当再次执行<code>while</code>循环时，结果仍然为真；直到<code>num = 0 </code>时，<code>while</code>的判断结果为假，因此跳出循环。</p>
<h3 id="while···else"><a href="#while···else" class="headerlink" title="while···else"></a><code>while···else</code></h3><p><code>while</code>循环可以配合<code>else</code>一起使用，当条件不再成立时，运行<code>else</code>中的代码块。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>num = <span class="number">5</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">while</span> num:</span><br><span class="line">        <span class="built_in">print</span>(num)</span><br><span class="line">        num -= <span class="number">1</span></span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;num为%d，判断结果为假，跳出循环。&quot;</span>%num)</span><br><span class="line">   </span><br><span class="line"></span><br><span class="line"><span class="comment">## 执行结果如下：</span></span><br><span class="line"><span class="number">5</span></span><br><span class="line"><span class="number">4</span></span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="number">2</span></span><br><span class="line"><span class="number">1</span>   <span class="comment">## 下一次循环时，num的值为0，while判断结果为假，因此将执行else语句</span></span><br><span class="line">num为<span class="number">0</span>，判断结果为假，跳出循环。</span><br></pre></td></tr></table></figure>

<blockquote>
<p>注意，由于是在python的idle中做的实验，上述代码虽然显示（肉眼所见）while和else为不同缩进，但其实是同一缩进。</p>
</blockquote>
<p>如果在上述<code>while</code>代码块中，将<code>num -= 1</code>变换成<code>num += 1</code>，由于判断结果永远为真（num &gt;&#x3D; 5 ，恒为真），因此会无限制的输出。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>num = <span class="number">5</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">while</span> num:</span><br><span class="line">        <span class="built_in">print</span>(num)</span><br><span class="line">        num += <span class="number">1</span></span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;num为%d，判断结果为假，跳出循环。&quot;</span>%num)</span><br><span class="line">        </span><br><span class="line"><span class="comment">## 执行结果如下：</span></span><br><span class="line"><span class="number">5</span></span><br><span class="line"><span class="number">6</span></span><br><span class="line">··· <span class="comment">## 若不使用ctrl + c结束代码执行，则代码输出结果可至无穷大的整数</span></span><br></pre></td></tr></table></figure>

<h3 id="跳出循环"><a href="#跳出循环" class="headerlink" title="跳出循环"></a>跳出循环</h3><h4 id="中止循环：exit"><a href="#中止循环：exit" class="headerlink" title="中止循环：exit"></a>中止循环：<code>exit</code></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">C:\Users\rushiy&gt;python</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>num = <span class="number">5</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">while</span> num:</span><br><span class="line">         <span class="built_in">print</span>(num)</span><br><span class="line">         num += <span class="number">1</span></span><br><span class="line">         <span class="keyword">if</span> num == <span class="number">10</span>:</span><br><span class="line">            exit()        <span class="comment"># 不仅跳出while循环，还将跳出脚本或python交互式命令行</span></span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">         <span class="built_in">print</span>(<span class="string">&quot;num为%d，判断结果为假，跳出循环。&quot;</span>%num)</span><br><span class="line"></span><br><span class="line">C:\Users\rushiy&gt;      <span class="comment"># 直接退出了交互式命令行</span></span><br><span class="line"><span class="comment">## 输出结果如下：</span></span><br><span class="line"><span class="number">5</span></span><br><span class="line"><span class="number">6</span></span><br><span class="line"><span class="number">7</span></span><br><span class="line"><span class="number">8</span></span><br><span class="line"><span class="number">9</span> </span><br></pre></td></tr></table></figure>

<blockquote>
<p>值得注意的是，通过<code>exit()</code>执行的中止循环，不仅中止了<code>while</code>，也跳出了python脚本。如果是在python的idle中执行的代码，则将退出python交互式命令行。</p>
</blockquote>
<h4 id="跳出当前循环：break"><a href="#跳出当前循环：break" class="headerlink" title="跳出当前循环：break"></a>跳出当前循环：break</h4><p>如果使用 <code>break</code> 语句，即使<code>while</code>条件为真，我们也可以停止循环：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>num = <span class="number">5</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">while</span> num:</span><br><span class="line">         <span class="built_in">print</span>(num)</span><br><span class="line">         num += <span class="number">1</span></span><br><span class="line">         <span class="keyword">if</span> num == <span class="number">10</span>:</span><br><span class="line">            <span class="keyword">break</span>        <span class="comment">## 跳出while循环，不跳出脚本</span></span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">         <span class="built_in">print</span>(<span class="string">&quot;num为%d，判断结果为假，跳出循环。&quot;</span>%num)</span><br><span class="line">        </span><br><span class="line"><span class="comment">## 输出结果如下：</span></span><br><span class="line"><span class="number">5</span></span><br><span class="line"><span class="number">6</span></span><br><span class="line"><span class="number">7</span></span><br><span class="line"><span class="number">8</span></span><br><span class="line"><span class="number">9</span></span><br></pre></td></tr></table></figure>

<h4 id="跳过当次循环：continue"><a href="#跳过当次循环：continue" class="headerlink" title="跳过当次循环：continue"></a>跳过当次循环：continue</h4><p>如果使用 <code>continue</code> 语句，我们可以停止当前的迭代，并继续下一个：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>num = <span class="number">5</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">while</span> num:</span><br><span class="line">         num -= <span class="number">1</span></span><br><span class="line">         <span class="keyword">if</span> num == <span class="number">3</span>:</span><br><span class="line">            <span class="keyword">continue</span></span><br><span class="line">         <span class="built_in">print</span>(num)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">         <span class="built_in">print</span>(<span class="string">&quot;num为%d，判断结果为假，跳出循环。&quot;</span>%num)</span><br><span class="line">        </span><br><span class="line"><span class="comment">## 输出结果如下：</span></span><br><span class="line"><span class="number">4</span></span><br><span class="line"><span class="number">2</span></span><br><span class="line"><span class="number">1</span></span><br><span class="line"><span class="number">0</span></span><br></pre></td></tr></table></figure>

<h2 id="for循环"><a href="#for循环" class="headerlink" title="for循环"></a>for循环</h2><p><code>for</code> 循环用于迭代序列（即列表，元组，字典，集合或字符串）。这与其他编程语言中的 <code>for</code> 关键字不太相似，而是更像其他面向对象编程语言中的迭代器方法。通过使用 <code>for</code> 循环，我们可以为列表、元组、集合中的每个项目等执行一组语句。</p>
<h3 id="常规用法-1"><a href="#常规用法-1" class="headerlink" title="常规用法"></a>常规用法</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>):</span><br><span class="line">      <span class="built_in">print</span>(x)</span><br></pre></td></tr></table></figure>

<p>for循环也可以配置else使用。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>):</span><br><span class="line">      <span class="built_in">print</span>(x)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">      <span class="built_in">print</span>(<span class="string">&quot;Finally finished!&quot;</span>)</span><br></pre></td></tr></table></figure>

<h3 id="遍历字符串、元组、列表、字典"><a href="#遍历字符串、元组、列表、字典" class="headerlink" title="遍历字符串、元组、列表、字典"></a>遍历字符串、元组、列表、字典</h3><ul>
<li>字符串</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> i <span class="keyword">in</span> <span class="string">&quot;Python&quot;</span>:</span><br><span class="line">        <span class="built_in">print</span>(i)</span><br><span class="line">   </span><br><span class="line">P</span><br><span class="line">y</span><br><span class="line">t</span><br><span class="line">h</span><br><span class="line">o</span><br><span class="line">n</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> i <span class="keyword">in</span> <span class="string">&quot;Python&quot;</span>:</span><br><span class="line">      <span class="built_in">print</span>(i, end=<span class="string">&quot; &quot;</span>)</span><br><span class="line">   </span><br><span class="line">P y t h o n &gt;&gt;&gt;   <span class="comment"># 由于设定了print()函数的结尾符为&quot; &quot;(空格)，因此此处不会换行</span></span><br></pre></td></tr></table></figure>

<ul>
<li>列表</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>names = [<span class="string">&quot;zhangsan&quot;</span>, <span class="string">&quot;lisi&quot;</span>, <span class="string">&quot;Tony&quot;</span>]</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> name <span class="keyword">in</span> names:</span><br><span class="line">      <span class="built_in">print</span>(name)</span><br><span class="line"></span><br><span class="line">zhangsan</span><br><span class="line">lisi</span><br><span class="line">Tony</span><br></pre></td></tr></table></figure>

<ul>
<li>元组</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>names = (<span class="string">&quot;zhangsan&quot;</span>, <span class="string">&quot;lisi&quot;</span>, <span class="string">&quot;Tony&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> name <span class="keyword">in</span> names:</span><br><span class="line">       <span class="built_in">print</span>(name)</span><br><span class="line"></span><br><span class="line">zhangsan</span><br><span class="line">lisi</span><br><span class="line">Tony</span><br></pre></td></tr></table></figure>

<ul>
<li>字典</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>scores = &#123;<span class="string">&#x27;zhangsan&#x27;</span>: <span class="number">150</span>, <span class="string">&#x27;lisi&#x27;</span>: <span class="number">150</span>, <span class="string">&#x27;Tony&#x27;</span>: <span class="number">145</span>&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">## 方法1：</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> item <span class="keyword">in</span> scores:</span><br><span class="line"><span class="meta">... </span>    <span class="built_in">print</span>(item, scores.get(item))</span><br><span class="line">...</span><br><span class="line">zhangsan <span class="number">150</span></span><br><span class="line">lisi <span class="number">150</span></span><br><span class="line">Tony <span class="number">145</span></span><br><span class="line"></span><br><span class="line"><span class="comment">## 方法2：</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> k,v <span class="keyword">in</span> scores.items():</span><br><span class="line"><span class="meta">... </span>    <span class="built_in">print</span>(k, v)</span><br><span class="line">...</span><br><span class="line">zhangsan <span class="number">150</span></span><br><span class="line">lisi <span class="number">150</span></span><br><span class="line">Tony <span class="number">145</span></span><br></pre></td></tr></table></figure>

<h3 id="跳出循环-1"><a href="#跳出循环-1" class="headerlink" title="跳出循环"></a>跳出循环</h3><p>跳出<code>for</code>循环跟跳出<code>while</code>循环一样。</p>
<h4 id="中止循环：exit-1"><a href="#中止循环：exit-1" class="headerlink" title="中止循环：exit"></a>中止循环：<code>exit</code></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>names = [<span class="string">&quot;zhangsan&quot;</span>, <span class="string">&quot;lisi&quot;</span>, <span class="string">&quot;Tony&quot;</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> x <span class="keyword">in</span> names:</span><br><span class="line">      <span class="keyword">if</span> x == <span class="string">&quot;lisi&quot;</span>:</span><br><span class="line">        exit()</span><br><span class="line">      <span class="built_in">print</span>(x)</span><br><span class="line"></span><br><span class="line"><span class="comment">## 输出结果为</span></span><br><span class="line">zhangsan   <span class="comment">## 并跳出脚本或python交互式命令行</span></span><br></pre></td></tr></table></figure>

<h4 id="跳出当前循环：break-1"><a href="#跳出当前循环：break-1" class="headerlink" title="跳出当前循环：break"></a>跳出当前循环：<code>break</code></h4><p>通过使用<code>break</code>语句，我们可以在循环遍历所有项目之前停止循环。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>names = [<span class="string">&quot;zhangsan&quot;</span>, <span class="string">&quot;lisi&quot;</span>, <span class="string">&quot;Tony&quot;</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> x <span class="keyword">in</span> names:</span><br><span class="line">      <span class="keyword">if</span> x == <span class="string">&quot;lisi&quot;</span>:</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">      <span class="built_in">print</span>(x)</span><br><span class="line">        </span><br><span class="line"><span class="comment">## 输出结果为：</span></span><br><span class="line">zhangsan    <span class="comment">## 结束for循环，不跳出脚本和python交互式命令行</span></span><br></pre></td></tr></table></figure>

<h4 id="跳出当次循环：continue"><a href="#跳出当次循环：continue" class="headerlink" title="跳出当次循环：continue"></a>跳出当次循环：<code>continue</code></h4><p>通过使用<code>continue</code>语句，我们可以停止循环的当前迭代，并继续下一个。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>names = [<span class="string">&quot;apple&quot;</span>, <span class="string">&quot;lisi&quot;</span>, <span class="string">&quot;Tony&quot;</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">for</span> x <span class="keyword">in</span> names:</span><br><span class="line">    <span class="keyword">if</span> x == <span class="string">&quot;lisi&quot;</span>:</span><br><span class="line">      <span class="keyword">continue</span></span><br><span class="line">    <span class="built_in">print</span>(x)</span><br><span class="line"></span><br><span class="line"><span class="comment">## 输出结果</span></span><br><span class="line">zhangsan</span><br><span class="line">Tony</span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://rushiy.gitee.io">rushiy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://rushiy.gitee.io/python/%E5%BE%AA%E7%8E%AF%E8%AF%AD%E5%8F%A5/">https://rushiy.gitee.io/python/%E5%BE%AA%E7%8E%AF%E8%AF%AD%E5%8F%A5/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://rushiy.gitee.io" target="_blank">如是的学习博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/python/">python</a></div><div class="post_share"><div class="social-share" data-image="" data-sites="wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/favicon.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">rushiy</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">28</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">3</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><div class="card-info-social-icons is-center"><a class="social-icon" href="mailto:rushiy@reg.email.cn" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#while-%E5%BE%AA%E7%8E%AF"><span class="toc-number">1.</span> <span class="toc-text">while 循环</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E8%A7%84%E7%94%A8%E6%B3%95"><span class="toc-number">1.1.</span> <span class="toc-text">常规用法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#while%C2%B7%C2%B7%C2%B7else"><span class="toc-number">1.2.</span> <span class="toc-text">while···else</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%B7%B3%E5%87%BA%E5%BE%AA%E7%8E%AF"><span class="toc-number">1.3.</span> <span class="toc-text">跳出循环</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%AD%E6%AD%A2%E5%BE%AA%E7%8E%AF%EF%BC%9Aexit"><span class="toc-number">1.3.1.</span> <span class="toc-text">中止循环：exit</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%B7%B3%E5%87%BA%E5%BD%93%E5%89%8D%E5%BE%AA%E7%8E%AF%EF%BC%9Abreak"><span class="toc-number">1.3.2.</span> <span class="toc-text">跳出当前循环：break</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%B7%B3%E8%BF%87%E5%BD%93%E6%AC%A1%E5%BE%AA%E7%8E%AF%EF%BC%9Acontinue"><span class="toc-number">1.3.3.</span> <span class="toc-text">跳过当次循环：continue</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#for%E5%BE%AA%E7%8E%AF"><span class="toc-number">2.</span> <span class="toc-text">for循环</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E8%A7%84%E7%94%A8%E6%B3%95-1"><span class="toc-number">2.1.</span> <span class="toc-text">常规用法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%81%8D%E5%8E%86%E5%AD%97%E7%AC%A6%E4%B8%B2%E3%80%81%E5%85%83%E7%BB%84%E3%80%81%E5%88%97%E8%A1%A8%E3%80%81%E5%AD%97%E5%85%B8"><span class="toc-number">2.2.</span> <span class="toc-text">遍历字符串、元组、列表、字典</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%B7%B3%E5%87%BA%E5%BE%AA%E7%8E%AF-1"><span class="toc-number">2.3.</span> <span class="toc-text">跳出循环</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%AD%E6%AD%A2%E5%BE%AA%E7%8E%AF%EF%BC%9Aexit-1"><span class="toc-number">2.3.1.</span> <span class="toc-text">中止循环：exit</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%B7%B3%E5%87%BA%E5%BD%93%E5%89%8D%E5%BE%AA%E7%8E%AF%EF%BC%9Abreak-1"><span class="toc-number">2.3.2.</span> <span class="toc-text">跳出当前循环：break</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%B7%B3%E5%87%BA%E5%BD%93%E6%AC%A1%E5%BE%AA%E7%8E%AF%EF%BC%9Acontinue"><span class="toc-number">2.3.3.</span> <span class="toc-text">跳出当次循环：continue</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/django/Django%E6%A8%A1%E6%9D%BF%E7%B3%BB%E7%BB%9F/" title="Django模板系统"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Django模板系统"/></a><div class="content"><a class="title" href="/django/Django%E6%A8%A1%E6%9D%BF%E7%B3%BB%E7%BB%9F/" title="Django模板系统">Django模板系统</a><time datetime="2022-11-04T07:08:03.000Z" title="发表于 2022-11-04 15:08:03">2022-11-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/django/Django%E8%A7%86%E5%9B%BE/" title="Django视图"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Django视图"/></a><div class="content"><a class="title" href="/django/Django%E8%A7%86%E5%9B%BE/" title="Django视图">Django视图</a><time datetime="2022-11-03T07:07:51.000Z" title="发表于 2022-11-03 15:07:51">2022-11-03</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/django/Django%E8%B7%AF%E7%94%B1%E7%B3%BB%E7%BB%9F/" title="Django路由系统"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Django路由系统"/></a><div class="content"><a class="title" href="/django/Django%E8%B7%AF%E7%94%B1%E7%B3%BB%E7%BB%9F/" title="Django路由系统">Django路由系统</a><time datetime="2022-11-02T07:07:34.000Z" title="发表于 2022-11-02 15:07:34">2022-11-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/django/%E8%B5%B0%E8%BF%9BDjango/" title="走进Django"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="走进Django"/></a><div class="content"><a class="title" href="/django/%E8%B5%B0%E8%BF%9BDjango/" title="走进Django">走进Django</a><time datetime="2022-11-01T07:01:20.000Z" title="发表于 2022-11-01 15:01:20">2022-11-01</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/python/python%E5%B8%B8%E7%94%A8%E6%A8%A1%E5%9D%97/" title="python常用模块"><img src="" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="python常用模块"/></a><div class="content"><a class="title" href="/python/python%E5%B8%B8%E7%94%A8%E6%A8%A1%E5%9D%97/" title="python常用模块">python常用模块</a><time datetime="2022-10-28T15:34:07.000Z" title="发表于 2022-10-28 23:34:07">2022-10-28</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 By rushiy</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"></div><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>